package com.ic.loan.activity

import android.os.Bundle
import android.view.View
import android.widget.TextView
import androidx.appcompat.widget.LinearLayoutCompat
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.lifecycle.lifecycleScope
import com.blankj.utilcode.util.*
import com.gyf.immersionbar.ImmersionBar
import com.ic.loan.R
import com.ic.loan.bean.MyInfo
import com.ic.loan.cache.Constant
import com.ic.loan.http.ApiUrl
import com.ic.loan.http.HttpUtils
import com.ic.loan.http.ResultListener
import com.ic.loan.pop.RedEnvelopePop
import com.lxj.xpopup.XPopup
import kotlinx.android.synthetic.main.activity_my_infomation.*
import kotlinx.android.synthetic.main.activity_start.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.math.BigDecimal
import java.math.BigInteger
import java.math.RoundingMode
import java.text.DecimalFormat
import java.text.NumberFormat

class StartActivity : BaseActivity() {
    private var per: BigDecimal? = null
    private var interest: BigDecimal? = null
    private val rate = 0.038
    private val min = 5000
    private val max = 10000000
    private val loanAmounts = mutableListOf<Int>(
        min,
        10000,
        20000,
        30000,
        40000,
        50000,
        60000,
        70000,
        80000,
        90000,
        100000,
        150000,
        200000,
        300000,
        400000,
        500000,
        600000,
        700000,
        800000,
        900000,
        1000000,
        2000000,
        3000000,
        4000000,
        5000000,
        6000000,
        7000000,
        8000000,
        9000000,
        max
    )
    private val months = mutableListOf<Int>(
        3, 6, 9, 12, 24, 36
    )
    private var currentMonth = months[0]
    private var currentIndex: Int = 0
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_start)
        ImmersionBar.setStatusBarView(this, spStatusBar)
        ivLogout.setOnClickListener { onBackPressed() }
        tvApply.setOnClickListener {
           getStatus()
        }
        ivAdd.setOnClickListener {
            if (currentIndex >= loanAmounts.size - 1) {
                return@setOnClickListener
            }
            currentIndex += 1
            changeBarPosition()
        }
        ClickUtils.expandClickArea(ivAdd, ConvertUtils.dp2px(50f))
        ClickUtils.expandClickArea(ivSub, ConvertUtils.dp2px(50f))
        ivSub.setOnClickListener {
            if (currentIndex <= 0) {
                return@setOnClickListener
            }
            currentIndex -= 1
            changeBarPosition()
        }
        ivLogout.setOnClickListener {
            XPopup.Builder(this).asConfirm(
                StringUtils.getString(R.string.tips),
                StringUtils.getString(R.string.tips_content),
                StringUtils.getString(R.string.cancel),
                StringUtils.getString(R.string.yes), {
                    logout()
                }, {}, false
            ).show()
        }
        mutableListOf<LinearLayoutCompat>(item1, item2, item3, item4, item5, item6)?.let { views ->
            views.forEach {
                it.setOnClickListener { view ->
                    currentMonth = months[views.indexOf(view)]
                    computePerAndInterest(loanAmounts[currentIndex], currentMonth)
                    views.forEach { item ->
                        if (item == view) {
                            item.setBackgroundResource(R.drawable.shape_item_bg_select)
                            (item.getChildAt(0) as TextView).setTextColor(
                                ColorUtils.getColor(
                                    android.R.color.white
                                )
                            )
                            (item.getChildAt(1) as TextView).setTextColor(
                                ColorUtils.getColor(
                                    android.R.color.white
                                )
                            )
                        } else {
                            item.setBackgroundResource(R.drawable.shape_item_bg_default)
                            (item.getChildAt(0) as TextView).setTextColor(ColorUtils.getColor(R.color.color_f37e20))
                            (item.getChildAt(1) as TextView).setTextColor(ColorUtils.getColor(R.color.color_f37e20))
                        }
                    }
                }
            }
            lifecycleScope.launch(Dispatchers.Default) {
                delay(200)
                withContext(Dispatchers.Main) {
                    views[0].performClick()
                }
            }
        }
        currentMonth = months[0]
        changeBarPosition()
        marqueeView.startWithList(
            mutableListOf(
                "915***28 Successful loan 100000",
                "971***14 Successful loan 200000",
                "917***69 Successful loan 50000",
                "759***43 Successful loan 150000",
                "719***68 Successful loan 80000",
                "964***37 Successful loan 100000",
                "915***88 Successful loan 300000",
                "957***33 Successful loan 50000",
                "915***88 Successful loan 300000",
                "915***88 Successful loan 300000",
            )
        )
    }

    private fun getStatus() {
        showLoading()
        HttpUtils.postOkGo(
            mutableMapOf(
                "amount" to loanAmounts[currentIndex].toString(),
                "term" to currentMonth,
                "repay_amount_per" to per.toString(),
                "monthly_interest" to interest.toString()
            ),
            ApiUrl.POST_LOAN_APPLY_LOAN,
            object : ResultListener() {
                override fun onSucceeded(json: String?) {
                    SPUtils.getInstance().put(Constant.APPLY_SUCCESS,1)
                    ActivityUtils.startActivity(MyInformationActivity::class.java)
                    onBackPressed()
                }

                override fun onLoadFinish() {
                    hintLoading()
                }
            })
    }

    private fun logout() {
        showLoading()
        HttpUtils.postOkGo(
            mutableMapOf("timestamp" to System.currentTimeMillis() / 1000),
            ApiUrl.POST_LOGOUT,
            object : ResultListener() {
                override fun onSucceeded(json: String?) {
                    SPUtils.getInstance().remove(Constant.TOKEN)
                    SPUtils.getInstance().remove(Constant.APPLY_SUCCESS)
                    onBackPressed()
                    ActivityUtils.startActivity(LoginActivity::class.java)
                }

                override fun onLoadFinish() {
                    super.onLoadFinish()
                    hintLoading()
                }
            })
    }

    private fun changeBarPosition() {
        var params = vBar.layoutParams as ConstraintLayout.LayoutParams
        params.circleAngle = ((270 + ((currentIndex + 1) * 180 / loanAmounts.size)).toFloat())
        vBar.layoutParams = params

        arcSeekBar.progress = ((currentIndex + 1) * 100 / loanAmounts.size)
        val formatter: NumberFormat = DecimalFormat("#,###.##")
        val formattedNumber: String = formatter.format(loanAmounts[currentIndex])
        tvAmount.text = formattedNumber
        computePerAndInterest(loanAmounts[currentIndex], currentMonth)
    }

    private fun computePerAndInterest(inputAmount: Int, cycle: Int) {
        interest = BigDecimal.valueOf(inputAmount.toDouble()).multiply(BigDecimal(rate)).divide(BigDecimal(cycle), 2, RoundingMode.HALF_UP)
        per = BigDecimal.valueOf(inputAmount.toDouble()).multiply(BigDecimal(rate))
            .divide(BigDecimal(cycle), 2, RoundingMode.HALF_UP).add(BigDecimal.valueOf(inputAmount.toDouble())
                .divide(BigDecimal(cycle), 2, RoundingMode.HALF_UP))
        val formatter: NumberFormat = DecimalFormat("#,###.##")
        tvInterest.text = "₹ ${formatter.format(interest)}"
        tvPer.text = "₹ ${formatter.format(per)}"
    }
}